package ejb;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.Myuser;
import model.Tag;

@Stateless

public class UserFacadeEJB implements UserFacadeEJBRemote {

	@PersistenceContext
	EntityManager em;

	@Override
	public boolean validate(String username, String password) {
		//EntityManager em=emf.createEntityManager();
		String sql="select u from Myuser u where u.username=:name and u.password=:pwd";
    	Query query= em.createQuery(sql);
    	query.setParameter("name", username);
    	query.setParameter("pwd", password);
    	if(query.getResultList().isEmpty()){
    		return false;
    	}
    	else return true;
	}

	@Override
	public boolean createUser(String username, String password) {
		//EntityManager em=emf.createEntityManager();
		//UserTransaction ut=null;
		Myuser user=new Myuser();
		user.setUsername(username);
		user.setPassword(password);
		user.setAuthority("personal user");
		em.persist(user);
		return true;
	}
	
	@Override
	public boolean createUser(String username, String passwordr,
			String authority) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean deleteUser(int userid) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Myuser findUserByName(String username) {
		String sql="select u from Myuser u where u.username=:name";
		Query query=em.createQuery(sql);
		query.setParameter("name", username);
		Myuser user=new Myuser();
		if(query.getResultList().size()!=0){
		user=(Myuser)query.getResultList().get(0);
		}
		else user=null;
		return user;
	}

	@Override
	public List<Myuser> getUserByAuthority(String authority) {
		try
    	{
			String sql = "select u from Myuser u where u.authority=:input";
			Query query = em.createQuery(sql);
			query.setParameter("input", authority);
			List<Myuser> result = query.getResultList();
			return result;
	    }
    	catch (RuntimeException re)
		{
			System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
			throw re;
		}		
	}
	

	@Override
	public boolean isNameExist(String username) {
    	if(this.findUserByName(username)!=null){
    		return true;
    	}
    	else return false;
	}

	@Override
	public Myuser findUserByID(int userid){
		String sql="select u from Myuser u where u.userid=:id";
		Query query=em.createQuery(sql);
		query.setParameter("id", userid);
		Myuser user=(Myuser)query.getResultList().get(0);
		return user;
	}
	
	public List<Myuser> getAllUser(){
		try
    	{
			String sql = "select u from Myuser u";
			Query query = em.createQuery(sql);
			List<Myuser> result = query.getResultList();
			return result;
	    }
    	catch (RuntimeException re)
		{
			System.out.println("getStudentInfo() failed : \n msg:"+ re.getMessage());
			throw re;
		}	
	}

	


}
